import categoryApi from "@/api/pro/categoryApi"


const state = {
  category1Id: undefined,
  category2Id: undefined,
  category3Id: undefined,
  category1List: [], // 1级分类的下拉数据
  category2List: [], // 2级分类的下拉数据
  category3List: [], // 3级分类的下拉数据
}

const mutations = {
  GETCATEGORY1LIST(state,data){
    state.category1List = data
  },
  GETCATEGORY2LIST(state,data){
    state.category2List = data
  },
  GETCATEGORY3LIST(state,data){
    state.category3List = data
  },
  GETCATEGORY1ID(state,data){
    state.category1Id = data
  },
  GETCATEGORY2ID(state,data){
    state.category2Id = data
  },
  GETCATEGORY3ID(state,data){
    state.category3Id = data
  },
}

const actions = {
  // 获取一级分类列表
  async getCategory1List({commit}) {
    // 调接口
    try {
      let result = await categoryApi.getCategory1()
      if(result.code === 200){
        commit('GETCATEGORY1LIST',result.data)
      }
    } catch (error) {
      console.log('获取一级分类数据失败,请重试')  ;      
    }
  },
  // 获取二级分类列表
  async getCategory2List({commit,state}) {
    // 将2级和3级的所有相关数据都清空
    state.category2Id = undefined;
    state.category3Id = undefined;
    state.category2List = [];
    state.category3List = [];
    // 调接口
    try {
      let result = await categoryApi.getCategory2(state.category1Id)
      if(result.code === 200){
        commit('GETCATEGORY2LIST',result.data)
      }
    } catch (error) {
      console.log('获取二级分类数据失败,请重试')  ;      
    }
  },
  // 获取三级分类列表
  async getCategory3List({commit,state}) {
    // 将3级的所有相关数据都清空
    state.category3Id = undefined;
    state.category3List = [];
    // 调接口
    try {
      let result = await categoryApi.getCategory3(state.category2Id)
      if(result.code === 200){
        commit('GETCATEGORY3LIST',result.data)
      }
    } catch (error) {
      console.log('获取三级分类数据失败,请重试')  ;      
    }
  },
}

export default {
  state,
  actions,
  mutations,
  namespaced: true,
}
